/*
 * Copyright (c) 2010 Sun Microsystems, Inc.
 * Copyright (c) 2011 Oracle Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

package org.sunspotworld.demo;

import com.sun.spot.core.peripheral.Spot;
import com.sun.spot.core.util.Properties;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Enumeration;
import com.sun.spot.wot.WebApplication;
import com.sun.spot.wot.http.HttpResponse;
import com.sun.spot.wot.http.HttpRequest;

/**
 *
 * @author vgupta
 */
public class PropertiesManager extends WebApplication {
    public void init() {};

    public PropertiesManager(String str) {
        super(str);
    }
    
    public synchronized HttpResponse processRequest(HttpRequest request) throws IOException {
        HttpResponse response = new HttpResponse();
        String path = request.getPathInfo();
        StringBuffer sb = null;

        if (request.getMethod().equalsIgnoreCase("GET")) {
            if (path.equals("/") || path.equals("")) {
                response.setBody(getPropertiesResponse(null).toString().getBytes());
            } else {
                sb = getPropertiesResponse(path.substring(1));
                if (sb == null) {
                    response.setStatus(HttpResponse.SC_NOT_FOUND);
                    response.setHeader("Cache-Control", "max-age=10");
                    return response;
                } else {
                    response.setBody(sb.toString().getBytes());
                }
            }
            
            response.setStatus(HttpResponse.SC_OK);
            response.setHeader("Content-Type", "text/plain");
            response.setHeader("Cache-Control", "max-age=10");
            return response;
        } else if (request.getMethod().equalsIgnoreCase("POST")) {
            if (!path.equals("/") && !path.equals("")) {
                response.setStatus(HttpResponse.SC_BAD_REQUEST);
                return response;
            } else {
                Properties oldProps = Spot.getInstance().getPersistentProperties();
                Properties newProps = new Properties();
                newProps.load(new ByteArrayInputStream(request.getBody()));
                Enumeration newKeys = newProps.keys();
                while (newKeys.hasMoreElements()) {
                    String newKey = (String) newKeys.nextElement();
                    oldProps.setProperty(newKey,
                            newProps.getProperty(newKey));
                }

                Spot.getInstance().storeProperties(oldProps);

                response.setBody(getPropertiesResponse(null).toString().getBytes());
                response.setStatus(HttpResponse.SC_OK);
                response.setHeader("Cache-Control", "max-age=10");
                return response;
            }
        } else if (request.getMethod().equalsIgnoreCase("DELETE")) {
            if (path.equals("/") || path.equals("")) {
                response.setStatus(HttpResponse.SC_BAD_REQUEST);
                return response;
            } else {
                Properties oldProps = Spot.getInstance().getPersistentProperties();
                if (oldProps.containsKey(path.substring(1))) {
                    oldProps.remove(path.substring(1));
                    Spot.getInstance().storeProperties(oldProps);
                    response.setBody(getPropertiesResponse(null).toString().getBytes());
                    response.setStatus(HttpResponse.SC_OK);
                    response.setHeader("Content-Type", "text/plain");
                    response.setHeader("Cache-Control", "max-age=10");
                    return response;
                } else {
                    response.setStatus(HttpResponse.SC_NOT_FOUND);
                    response.setHeader("Cache-Control", "max-age=10");
                    return response;
                }
            }
        } else {
            response.setStatus(HttpResponse.SC_METHOD_NOT_ALLOWED);
            response.setHeader("Allow", "GET, DELETE, POST");

            return response;
        }
    }

    private StringBuffer getPropertiesResponse(String key) {
        Properties prop = Spot.getInstance().getPersistentProperties();
        StringBuffer sb = new StringBuffer();
        String value;

        if (key != null) {
            if ((value = prop.getProperty(key)) == null)
                return null;
            else
                sb.append("\"" + value + "\"");

            return sb;
        }

        sb.append("{\n");
        if (prop != null) {
            for (Enumeration e = prop.propertyNames(); e.hasMoreElements();) {
                key = (String) e.nextElement();
                if (key == null) continue;
                value = prop.getProperty(key);
                sb.append("\t\"" + key + "\": \"" + value + "\",\n");
            }
        }

        sb.append("}\n");
        return sb;
    }
}
